"use strict";

import Vue from "vue";
import axios from "axios";
import qs from "qs";

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const baseURL = "/";

axios.defaults.headers.common = {
    "Accept": "application/json",
    "Authorization": "33012e58-3daf-4d28-b2cb-92fbe3aa256c ",
    "X-Requested-With": "XMLHttpRequest",
    "Access-Control-Allow-Origin": "*"
};
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

// 发送请求前处理request的数据
/* axios.defaults.transformRequest = [(data) => {
    // Do whatever you want to transform the data
    let newData = "";
    for (let k in data) {
        newData += encodeURIComponent(k) + "=" + encodeURIComponent(data[k]) + "&";
    }
    return newData;
}]; */

let config = {
    // baseURL: process.env.baseURL || process.env.apiUrl || ""
    baseURL: baseURL + "wit_harns_service/",
    timeout: 15000, // Timeout
    withCredentials: true // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
    function(config) {
    // Do something before request is sent
        if (config.method === "get") {
            return config;
        }
        config.data = qs.stringify(config.data);
        return config;
    },
    function(error) {
    // Do something with request error
        return Promise.reject(error);
    }
);

// Add a response interceptor
_axios.interceptors.response.use(
    function(response) {
    // Do something with response data
        return response;
    },
    function(error) {
    // Do something with response error
        return Promise.reject(error);
    }
);

Plugin.install = function(Vue, options) {
    Vue.axios = _axios;
    window.axios = _axios;
    Object.defineProperties(Vue.prototype, {
        axios: {
            get() {
                return _axios;
            }
        },
        $axios: {
            get() {
                return _axios;
            }
        }
    });
};

Vue.use(Plugin);

export default Plugin;
